package org.xems.utils
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;

	/**
	 * 
	 * @author qixiaowei
	 * 
	 */
	public class DisplayUtil
	{
		/**
		 * 删除一个容器内所有显示对象
		 * # 可以按需求，选择是否需要递归删除子集容器
		 * @param container
		 * @param recursionChild
		 * 
		 */
		public static function removeChildren(container:DisplayObjectContainer, recursionChild:Boolean = false):void
		{
			var len:uint = container.numChildren;
			while(len-->0){
				var child:DisplayObject = container.removeChildAt(0);
				if(child is DisplayObjectContainer && recursionChild){
					removeChildren(container, recursionChild);
				}
			}
		}
		/**
		 * 为显示对象设置一个非透明的HitArea区域
		 */
		public static function setNotTransparentHitArea(dsp:DisplayObject):Sprite
		{
			var sp:Sprite = new Sprite();
			sp.visible = false;
			sp.mouseEnabled = false;
			sp.mouseChildren = false;
			
			var bd:BitmapData;
			if(dsp is Bitmap){
				bd = Bitmap(dsp).bitmapData;
			}else{
				bd = new BitmapData(dsp.width, dsp.height, true, 0);
				bd.draw(dsp);
			}
			sp.graphics.clear();
			sp.graphics.beginFill(0);
			for(var x:uint=0;x<bd.width;x++)
			{
				for(var y:uint=0;y<bd.height;y++)
				{
					if(bd.getPixel32(x,y)){
						sp.graphics.drawRect(x,y,1,1);
					}
				}
			}
			//以graphics画出bd的无透明区域
			sp.graphics.endFill();
			if(dsp.parent){
				sp.x = dsp.x;
				sp.y = dsp.y;
				dsp.parent.addChild(sp);
			}else{
				dsp.addEventListener(Event.ADDED, 
					function(event:Event):void{
						dsp.parent.addChild(sp);
					}
				);
			}
			return sp;
		}
	}
}